package fa

import (
	"bytes"
	"io"
	"log"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"

	"gallery/crawler"
	"gallery/crawler/utils"

	"github.com/PuerkitoBio/goquery"
)

const (
	start = "https://www.furaffinity.net/gallery"
	host  = "https://www.furaffinity.net"
)

// parseLink 解析出主页面中的链接
func parseLink(selector, attr string, data []byte) []string {
	result := make([]string, 0)
	doc, _ := goquery.NewDocumentFromReader(bytes.NewReader(data))
	rs := doc.Find(selector)
	rs.Each(func(i int, e *goquery.Selection) {
		s, _ := e.Attr(attr)
		result = append(result, s)
	})
	return result
}

// get 发起一个get请求
func get(uri string) []byte {
	req := utils.MustRequest("GET", uri, nil)

	resp, err := crawler.MyClient.Do(req)
	if err != nil {
		log.Fatalln(crawler.Err("网络故障"))
	}
	defer resp.Body.Close()

	data, _ := io.ReadAll(resp.Body)
	return data
}

// 下载图片或者文件
func dFile(uri, dst string) {
	req := utils.MustRequest("GET", uri, nil)

	resp, err := crawler.MyClient.Do(req)
	if err != nil {
		log.Fatalln("网络故障")
	}
	defer resp.Body.Close()

	f, err := os.Create(dst)
	if err != nil {
		log.Println(crawler.Warn("创建文件<", dst, ">失败!"))
		return
	}
	io.Copy(f, resp.Body)
}

// checkEnd 检查是否到达尾页
func checkEnd(data []byte) bool {
	if strings.Contains(string(data), "no sub") {
		log.Println("到达尾页!")
		return true
	}
	return false
}

// genName 拼接图片的名称
func genName(dlink, alt string) string {
	// 去除不合法字符
	reg := regexp.MustCompile(`[:/?\s@,"'*]+`)
	alt = reg.ReplaceAllString(alt, "-")

	// 获取图片的id，并与alt拼接
	//log.Println(dlink)
	fullName := path.Base(dlink)
	id := fullName[:strings.Index(fullName, ".")]
	ext := path.Ext(dlink)
	return id + "." + alt + ext
}

// getSubmissions 获取提交数量和页数
func getSubmissions(user string) (int, int) {
	userPage, _ := utils.MustParseURL(host)
	userPage.Path = path.Join("user", user)
	page := get(userPage.String())
	doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page))
	if err != nil {
		log.Println(crawler.Warn("获取submission信息失败！"))
		return -1, -1
	}
	leftCell := doc.Find(".cell").First().Text()
	re := regexp.MustCompile(`Sub.+:\s?(\d.*)`)
	submissions, _ := strconv.Atoi(re.FindStringSubmatch(leftCell)[1])
	return submissions, submissions/72 + 1
}
